#include <QBuffer>
#include <QCryptographicHash>
#include "imagechange.h"

ImageChange::ImageChange(int newRev, int newUser, int newDoc, int newPos, int newWidth, int newHeight, QByteArray data) :
        Change(Message::ADD_IMAGE, newRev, newUser, newDoc, newPos)
{
    width = newWidth;
    height = newHeight;
	imageData = data;
	operation = Message::ADD_IMAGE;
}

ImageChange::ImageChange(QByteArray bytes)
{
	QBuffer buffer(&bytes, 0);
	buffer.open(QIODevice::ReadOnly);
	QDataStream sin(&buffer);

    //get the operation
    quint8 op;
    sin >> op;
    operation = op;

    sin >> revisionId >> userId >> docId >> position >> width >> height;

	//get the image data
	qint64 dataSize;
	sin >> dataSize;
	imageData = buffer.read(dataSize);
}

QByteArray ImageChange::toBytes()
{
    QByteArray bytes;

	//create a buffer for the QByteArray bytes.
	//This allows us to easily write the image data to the bytearray
	QBuffer buffer(&bytes, 0);
	buffer.open(QIODevice::WriteOnly);

	QDataStream sout(&buffer);

    sout << operation << revisionId << userId << docId << position;
	sout << width << height;

	//write the imagedata to the buffer (which in turn writes to the byte array)
	sout << (qint64)imageData.size();
	buffer.write(imageData);

    return bytes;
}
